package com.ask.service.Impl;

import com.ask.context.BaseContext;
import com.ask.entity.AddressBook;
import com.ask.exception.BaseException;
import com.ask.mapper.AddressBookMapper;
import com.ask.result.Result;
import com.ask.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 获取用户的地址列表
     *
     * @return
     */
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }


    /**
     * 根据地址id获取地址信息
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    /**
     * 根据地址id修改地址
     *
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Override
    public void setDefaultAddress(AddressBook addressBook) {
        // 将当前用户的所有地址设置为非默认地址
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        // update address_book set is_default = #{isDefault} where user_id = #{userId}
        addressBookMapper.cancelDeafaultAddress(addressBook);

        // 设置当前id的地址为默认地址
        addressBook.setIsDefault(1);
        // update address_book set is_default = #{isDefault} where id = #{id}
        addressBookMapper.update(addressBook);
    }

}
